package cn.nuist.service.impl;

import cn.nuist.dao.UserDao;
import cn.nuist.entity.User;
import cn.nuist.entity.enu.UserRole;
import cn.nuist.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User login(String username, String password) {
        User user  = userDao.findByUserName(username);
        //System.out.println(user);
        if(ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名输入错误！");
        if(!user.getPassword().equals(password)){
            throw new RuntimeException("密码输入错误！");
        }
        return user;
    }

    @Override
    public ArrayList<User> getAllUser() {
        return userDao.getAllUser();
    }

    @Override
    public User getUserByName(String username) {
        User user = userDao.findByUserName(username);
        //System.out.println(username);
        //System.out.println(user);
        if(user == null){
            throw new RuntimeException("该用户不存在");
        }
        return user;
    }

    @Override
    public void addUser(String name, String username, String password, String rpassword, String role) {
        User userFindByUserName = userDao.findByUserName(username);
        //System.out.println("查询到的用户对象: " + userFindByUserName);
        if (userFindByUserName != null) {
            //System.out.println("用户名已存在: " + userFindByUserName.getUsername());
            throw new RuntimeException("用户名已存在！");
        }
        if(!password.equals(rpassword)) {
            throw new RuntimeException("两次输入的密码不匹配！");
        }
        User user = new User(username,password,name,UserRole.valueOf(role));
        userDao.addUser(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userDao.findByUserId(id);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public void delete(Integer id) {
        userDao.delete(id);
    }


}
